//
//  NWHomeTableViewController.swift
//  Weibo
//
//  Created by Northwan on 16/1/19.
//  Copyright © 2016年 Northwan. All rights reserved.
//

import UIKit
import SVProgressHUD

private let cellIdentifier = "CELL"

class NWHomeTableViewController: NWVisitorTableViewController {

    private var statusListViewModel = NWStatusListViewModel()
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        if !userlogon {
            visitorView .setupVisitorInfo(imgName:nil, message: nil)
            return
        }
        
        setupUI()
        loadDdata()
    }
    
    private func setupUI(){
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(imgName: "navigationbar_friendsearch", target: self, action: "friendsearch")
        
        tableView.registerClass(NWStatusCell.self, forCellReuseIdentifier: cellIdentifier)
        tableView.separatorStyle = .None
        
        //设置自动计算行高，会根据contentView的最大Y值来计算
        tableView.rowHeight = UITableViewAutomaticDimension
        //设置预估行高，主要是让其能够滚动开，滚动时会自动计算，（最好设置接近真实高度）
        tableView.estimatedRowHeight = 200
        
        tableView.tableFooterView = pullUpView
        
        mRefreshControl.addTarget(self, action: "loadDdata", forControlEvents: .ValueChanged)
        tableView.addSubview(mRefreshControl)
        
    }
    
    @objc private func friendsearch(){
        printLog(__FILE__)
        printLog(__LINE__)
        printLog(__FUNCTION__)
        
       navigationController?.pushViewController(NWTempViewController(), animated: true)
    }
    
    /**
     结束刷新
     */
    private func endLoad(){
        pullUpView.stopAnimating()
        mRefreshControl.endRefreshing()
    }
    
    
    // MARK: - 懒加载
    private lazy var pullUpView:UIActivityIndicatorView = {
        let view = UIActivityIndicatorView(activityIndicatorStyle:.WhiteLarge)
        view.color = UIColor.redColor()
        view.sizeToFit()
        return view
    }()
    /// 刷新控件
    private lazy var mRefreshControl:NWRefreshControl = NWRefreshControl()
    /// 刷新提示控件
    private lazy var topRefreshTipView:UILabel = {
        let tipView = UILabel()
        tipView.backgroundColor = UIColor.orangeColor()
        tipView.textColor = UIColor.whiteColor()
        tipView.textAlignment = .Center
        tipView.hidden = true
        return tipView
    }()
}

extension NWHomeTableViewController{
    @objc private func loadDdata(){
        statusListViewModel.loadDdata(pullUpView.isAnimating()) {(isSucessed,count) -> () in
            if isSucessed {
                self.tableView.reloadData()
                //只有在下拉刷新的时候才显示刷新条数
                if !self.pullUpView.isAnimating(){
                    self.showTipsView(count)
                }
            }else{
                SVProgressHUD.showErrorWithStatus("请求失败")
            }
            self.endLoad()
        }
    }
    
    
    /**
     显示顶部提示控件
     
     - parameter count: 新数据的条数
     */
    private func showTipsView(count:Int){
        //如果当前控件正在执行动画，直接返回
        if self.topRefreshTipView.hidden == false {
            return
        }
        
        //判断当前控件是否被添加过
        if self.topRefreshTipView.superview == nil{
            topRefreshTipView.frame = CGRect(x: 0, y: 64-35, width: SCREENW, height: 35)
            if let navCtrl = self.navigationController{
                navCtrl.view.insertSubview(self.topRefreshTipView, belowSubview: navCtrl.navigationBar)
            }
        }
        
        //设置数据
        if count  == 0{
            self.topRefreshTipView.text = "没有微博数据"
        }else{
            self.topRefreshTipView.text = "加载了\(count)条数据"
        }
        
        //执行动画
        self.topRefreshTipView.hidden = false
        
        UIView.animateWithDuration(0.5, animations: { () -> Void in
            self.topRefreshTipView.transform = CGAffineTransformMakeTranslation(0, self.topRefreshTipView.frame.height)
        }) { (_) -> Void in
            UIView.animateWithDuration(0.5, delay: 1, options: [], animations: { () -> Void in
                self.topRefreshTipView.transform = CGAffineTransformIdentity
                }, completion: { (_) -> Void in
                    self.topRefreshTipView.hidden = true
            })
        }
    }
}

extension NWHomeTableViewController{
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statusListViewModel.statusList?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! NWStatusCell
        cell.statusViewModel = statusListViewModel.statusList![indexPath.row]
        return cell
    }
    
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
    }
    
    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        if indexPath.row == statusListViewModel.statusList!.count - 1 && !pullUpView.isAnimating(){
             pullUpView.startAnimating()
             loadDdata()
        }
    }
}
